import { updateTrainingPlanUsingPost } from '@/services/backend/trainingPlanController';
import { listTrainingRuleVoByIdsUsingPost } from '@/services/backend/trainingRuleController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Modal } from 'antd';
import React from 'react';

interface Props {
  oldData?: API.TrainingPlan;
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.TrainingPlanUpdateRequest) => {
  const hide = message.loading('正在更新');
  const ids = fields.ruleList as number[];
  const res = await listTrainingRuleVoByIdsUsingPost({
    ids,
  });
  const rules = res?.data ?? [];
  const ruleList = rules.map((rule) => ({
    trainingRuleId: rule.id,
    ruleName: rule.ruleName,
    status: 0,
  })) as API.TrainingRuleDto[];
  try {
    await updateTrainingPlanUsingPost({
      ...fields,
      ruleList,
    });
    hide();
    message.success('更新成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(`更新失败${error.message}`);
    return false;
  }
};

const UpdateModal: React.FC<Props> = (props) => {
  const { modalVisible, onSubmit, onCancel, oldData } = props;

    const columns: ProColumns<API.TrainingPlanVO>[] = [
    {
      title: '计划名称',
      dataIndex: 'planName',
      valueType: 'text',
    },
    {
      title: '计划描述',
      dataIndex: 'description',
      valueType: 'text',
    },
    {
      title: '开始时间',
      sorter: true,
      dataIndex: 'startTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      sorter: true,
      dataIndex: 'endTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '计划状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '开启', status: 'active' },
        archived: { text: '关闭', status: 'inactive' },
      },
    }
  ];

  return (
    <Modal title={'更新'} open={modalVisible} destroyOnClose footer={null} onCancel={onCancel}>
      <ProTable
        type={'form'}
        columns={columns}
        form={{ initialValues: oldData }}
        onSubmit={async (value) => {
          const success = await handleUpdate({
            ...value,
            id: oldData?.id,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};
export default UpdateModal;
